using B.Z.BasicData.Infrastructure;
using B.Z.Inventory.API.Read.Application.Command;
using B.Z.Inventory.API.Read.DTO;
using B.Z.Inventory.Domain;
using B.Z.Inventory.ErrorCode;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.Z.Inventory.API.Read.Application.CommandHandler
{
    /// <summary>
    /// 库存预警查询命令处理器
    /// </summary>
    public class LowStockAlertCommandHandler : IRequestHandler<LowStockAlertCommand, APIResult<LowStockAlertDto>>
    {
        private readonly IBaseRepository<T_Goods> goodsRepository;
        private readonly ILogger<LowStockAlertCommandHandler> logger;

        public LowStockAlertCommandHandler(IBaseRepository<T_Goods> goodsRepository, ILogger<LowStockAlertCommandHandler> logger)
        {
            this.goodsRepository = goodsRepository;
            this.logger = logger;
        }

        public Task<APIResult<LowStockAlertDto>> Handle(LowStockAlertCommand request, CancellationToken cancellationToken)
        {
            APIResult<LowStockAlertDto> result = new APIResult<LowStockAlertDto>();
            result.Code = APIEnums.ok;

            try
            {
                // 获取所有未删除的货品数据
                var query = goodsRepository.GetAll()
                    .AsNoTracking()
                    .Where(x => !x.IsDelete);

                // 应用筛选条件
                if (request.StoreId.HasValue)
                {
                    // 这里可能需要根据实际的仓库货品关系表进行关联查询
                }

                var goods = query.ToList();
                var lowStockItems = new List<LowStockItem>();
                var checkTime = DateTime.Now;

                foreach (var item in goods)
                {
                    var currentStock = item.SystemNum ?? 0;
                    var minStock = item.MinStockLevel ?? 0;
                    var safeStock = item.SafeStockLevel ?? 0;

                    LowStockItem alertItem = null;

                    // 判断预警级别
                    if (currentStock <= 0)
                    {
                        // 缺货警告
                        alertItem = new LowStockItem
                        {
                            GoodsId = item.Id,
                            GoodsName = item.GoodsName,
                            GoodsNumber = item.GoodsNumber,
                            CurrentStock = currentStock,
                            MinStockLevel = minStock,
                            SafeStockLevel = safeStock,
                            AlertLevel = 3,
                            AlertDescription = "库存已耗尽，急需补货",
                            StockGap = minStock - currentStock,
                            AlertTime = checkTime
                        };
                    }
                    else if (currentStock <= minStock && minStock > 0)
                    {
                        // 低库存预警
                        alertItem = new LowStockItem
                        {
                            GoodsId = item.Id,
                            GoodsName = item.GoodsName,
                            GoodsNumber = item.GoodsNumber,
                            CurrentStock = currentStock,
                            MinStockLevel = minStock,
                            SafeStockLevel = safeStock,
                            AlertLevel = 1,
                            AlertDescription = "库存已低于最低库存阈值",
                            StockGap = minStock - currentStock,
                            AlertTime = checkTime
                        };
                    }
                    else if (currentStock <= safeStock && safeStock > 0)
                    {
                        // 安全库存预警
                        alertItem = new LowStockItem
                        {
                            GoodsId = item.Id,
                            GoodsName = item.GoodsName,
                            GoodsNumber = item.GoodsNumber,
                            CurrentStock = currentStock,
                            MinStockLevel = minStock,
                            SafeStockLevel = safeStock,
                            AlertLevel = 2,
                            AlertDescription = "库存已低于安全库存阈值",
                            StockGap = safeStock - currentStock,
                            AlertTime = checkTime
                        };
                    }

                    // 根据请求的预警级别过滤
                    if (alertItem != null && (!request.AlertLevel.HasValue || alertItem.AlertLevel == request.AlertLevel.Value))
                    {
                        lowStockItems.Add(alertItem);
                    }
                }

                // 按预警级别排序（级别高的在前）
                lowStockItems = lowStockItems.OrderByDescending(x => x.AlertLevel).ThenBy(x => x.StockGap).ToList();

                result.Data = new LowStockAlertDto
                {
                    TotalAlertCount = lowStockItems.Count,
                    CheckTime = checkTime,
                    LowStockItems = lowStockItems
                };

                logger.LogInformation($"成功获取库存预警，共{lowStockItems.Count}个预警项目");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取库存预警时发生错误");
                result.Code = APIEnums.fail;
                result.Message = "获取库存预警失败";
            }

            return Task.FromResult(result);
        }
    }
}